package com.group2.view;

import java.awt.EventQueue;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout.Alignment;
import javax.swing.table.DefaultTableModel;

import model.Book;

import javax.swing.LayoutStyle.ComponentPlacement;
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
import model.*;
import static model.netBase.IP;

public class LibraryBookReturnFrame extends JFrame {

	private JPanel contentPane;
	private JTable returntable;
	private JLabel lblNewLabel;
	private JButton btnNewButton;
	private static ArrayList<Book>list=null;
	private static String studentId;

	/**
	 * Launch the application.
	 */
//	public static void main(String[] args) {
//		EventQueue.invokeLater(new Runnable() {
//			public void run() {
//				try {
//					LibraryBookReturnFrame frame = new LibraryBookReturnFrame("09020324");
//					frame.setVisible(true);
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		});
//	}
	/**
	 * 拉取图书列表
	 */
	public void refresh() throws IOException, ClassNotFoundException {
		Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
		//设置超时时间
		socket.setSoTimeout(3000);
		//构建IO
		OutputStream os = socket.getOutputStream();
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
		bw.write("23"+'\n'+studentId+'\n');
		bw.flush();
		//从服务端输入到本地
		System.out.println("开始传输");
		InputStream is = socket.getInputStream();
		ObjectInputStream in = new ObjectInputStream(is);
		Object obj = in.readObject();
		list = (ArrayList<Book>) obj;
		System.out.println(list);
		//输出输入流关闭
		is.close();
		os.close();
		socket.close();
		System.out.println("传输结束");
	}
	/**
	 * Create the frame.
	 */
	public LibraryBookReturnFrame(String id, Timer time) throws IOException, ClassNotFoundException {
		studentId=id;
		setTitle("图书归还");
		setBounds(450, 200, 520, 350);
		this.setLocationRelativeTo(null);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		this.setResizable(false);
		JScrollPane scrollPane = new JScrollPane();
		time.start();
		this.addMouseMotionListener(new MouseMotionListener() {@Override public void mouseDragged(MouseEvent e) {}@Override public void mouseMoved(MouseEvent e) {time.stop();}});
		this.addMouseListener(new MouseListener() {@Override public void mouseClicked(MouseEvent e) {}@Override public void mousePressed(MouseEvent e) {}@Override public void mouseReleased(MouseEvent e) {}@Override public void mouseEntered(MouseEvent e) {time.start();}@Override public void mouseExited(MouseEvent e) {time.start();}});
		lblNewLabel = new JLabel("已借阅图书：");
		
		btnNewButton = new JButton("归还图书");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					bookReturnActionPerformed(e);
				} catch (IOException ex) {
					throw new RuntimeException(ex);
				} catch (ClassNotFoundException ex) {
					throw new RuntimeException(ex);
				}
			}
		});
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap(43, Short.MAX_VALUE)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
								.addComponent(lblNewLabel)
								.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 421, GroupLayout.PREFERRED_SIZE))
							.addGap(32))
						.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
							.addComponent(btnNewButton)
							.addGap(199))))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(32)
					.addComponent(lblNewLabel)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 190, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(btnNewButton)
					.addContainerGap(46, Short.MAX_VALUE))
		);
		
		returntable = new JTable();
		returntable.setModel(new DefaultTableModel(
			new Object[][] {},
			new String[] {
				"\u56FE\u4E66\u7F16\u53F7", "\u56FE\u4E66\u540D\u79F0", "\u4F5C\u8005", "\u51FA\u7248\u793E", "\u5F52\u8FD8\u671F\u9650"}){
			boolean[] canEdit = new boolean[]{false, false, false, false, false};
			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}

		});
		scrollPane.setViewportView(returntable);
		contentPane.setLayout(gl_contentPane);
		refresh();
		fillbooktable(list);
	}
	/**
	 * 初始化表格数据
	 */
	private void fillbooktable(ArrayList<Book> books) {
		DefaultTableModel dtm=(DefaultTableModel) returntable.getModel();
		dtm.setRowCount(0);//设为0行
		//连接数据库
		try {
			int size = books.size();
			int index = 0;
			while (size > 0) {
				Vector v = new Vector();
				v.add(books.get(index).getBookId());v.add(books.get(index).getBookName()) ;v.add(books.get(index).getBookAuthor());v.add(books.get(index).getBookPublisher());v.add(books.get(index).getBookReturnPeriod());
				dtm.addRow(v);
				size--;
				index++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 图书归还事件处理
	 */
	private void bookReturnActionPerformed(ActionEvent e) throws IOException, ClassNotFoundException {
		int row=-1;
		row=this.returntable.getSelectedRow();
		String bookID=String.valueOf(returntable.getValueAt(row, 0));
		if(row==-1)
		{
			JOptionPane.showMessageDialog(null,"请选择要归还的图书");
			return;
		}
		int n=JOptionPane.showConfirmDialog(null, "确定要归还本书吗？");
		if(n==0) {
			//连接数据库
			Socket socket = new Socket(IP(), 2000);//此处主机地址请自行修改
			//设置超时时间
			socket.setSoTimeout(3000);
			//构建IO
			OutputStream os = socket.getOutputStream();
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			bw.write("25"+'\n'+studentId+'\n'+bookID+'\n');
			bw.flush();
			//从服务端输入到本地
			System.out.println("开始传输");
			InputStream is=socket.getInputStream();
			BufferedReader br=new BufferedReader(new InputStreamReader(is));
			String flag=br.readLine();
			if(flag.equals("true")) {
				JOptionPane.showMessageDialog(null, "还书成功");
				refresh();
				fillbooktable(list);
			}else JOptionPane.showMessageDialog(null,"还书失败！");
			//输出输入流关闭
			is.close();
			os.close();
			socket.close();
			System.out.println("传输结束");
		}
		
		//连接数据库
	}

}
